import {
    reqConsumerDeviceMuffling,
    reqDeviceData,
    reqConsumerAlarmPage
  } from '../../../../request/api.js'
  import {
    showMsg
  } from '../../../../utils/config.js'
  const app = getApp()
  
  Page({
    data: {
      alarmList: [],
      deviceData: {},
      deviceData: {},
    },
  
    onLoad(options) {
      console.log(JSON.parse(options.deviceData), 'options');
      this.setData({
        deviceData: JSON.parse(options.deviceData)
      })
    //   this.getDeviceData() // imei查询最新设备数据
    //   this.getConsumerAlarmPage()  // 告警列表
    },
  
    onShow() {
      if(app.globalData.deviceInfo!=null){
        console.log(app.globalData.deviceInfo ,'deviceInfo');
        this.setData({
          "deviceData.deviceName":app.globalData.deviceInfo.deviceName,
          "deviceData.roomId":app.globalData.deviceInfo.roomId,
          "deviceData.roomName":app.globalData.deviceInfo.roomName
        })
        app.globalData.deviceInfo =null
        wx.setStorageSync('deviceInfo',null);
      }
    },
    // 历史记录
    onAlarm() {
      let deviceInfo = JSON.stringify({
        imei:this.data.deviceData.deviceCode,
        deviceType:this.data.deviceData.deviceType,
        flag:true
      })
      wx.navigateTo({
        url: `/packageA/pages/index-inside-page/alarmRecord/alarmRecord?deviceInfo=${deviceInfo}`,
      })
    },
    // imei查询最新设备数据
    async getDeviceData() {
      const res = await reqDeviceData(this.data.deviceData.deviceCode)
      if (res.code !== 20000) return showMsg(res.message)
      console.log(res,'imei查询最新设备数据');
      this.setData({
        deviceData: res.data.rows || {}
      })
    },
    
      // 点击复制imei
      clickCopyImei(e) {
        let {
          imei
        } = e.currentTarget.dataset
        console.log(e);
        console.log(imei);
        wx.setClipboardData({
          data: imei,
          success(res) {
            wx.getClipboardData({
              success(res) {
                showMsg(`${imei} 已复制`)
              }
            })
          }
        })
      },
      
     // 告警列表
      async getConsumerAlarmPage() {
        const res = await reqConsumerAlarmPage(1,50,{
          userId: app.globalData.userId,
          homeId: app.globalData.familyInfo.id,
          deviceCode:this.data.deviceData.deviceCode
        })
        if (res.code !== 20000) return showMsg(res.message)
        console.log(res);
        if(res.data.total==0) return
        // 找到最近的日期的告警数据（最多10条）
        const recentDate = res.data.rows.map(item => item.createTime.split(' ')[0]).reduce((a, b) => (a > b ? a : b)); // 找到最大的日期（最近的日期）
         let recentDate2 = res.data.rows
        .filter(item => item.createTime.startsWith(recentDate))
        .slice(0, 10);
        recentDate2.forEach(item=>{
          item.createTime2=   item.createTime.slice(-8)
        })
        console.log(recentDate2);
  
        this.setData({
          alarmList: recentDate2 || {}
        })
      },
  
  })